#!/usr/bin/env python

from pyfileutils import read_file, write_file
import sys

try:
    from xml.etree import cElementTree as ET
except ImportError:
    try:
        from xml.etree import ElementTree as ET
    except ImportError:
        try:
            import cElementTree as ET
        except ImportError:
            try:
                from elementtree import ElementTree as ET
            except ImportError:
                raise Exception("Could not import ElementTree")

class Row(dict):

    """A Row represents a database row.
    
    Creation of Rows is not done through a Row object, rather,
    new rows are INSERTed into a Table, which will then yield Rows
    given the appropriate SELECT statement.  Row only writes to disk
    when its columns' values are changed or its columns are deleted
    outright.
    
    """

    def __init__(self, lockfile):
        """Initializes a Row.

        lockfile: a LockFile instance.

        """
        self.file = lockfile
        data = self.file.get_contents()
        c = ET.fromstring(data).getchildren()
        # c = ET.parse(self.filename).getroot().getchildren()
        dict.__init__(self, dict([(e.tag, e.text) for e in c]))

    def debug_items(self):
        out = []
        for a, b in self.items():
            try:
                c = str(a)[:30]
            except:
                c = "<cannot serialize>"
            try:
                d = str(b)[:30]
            except:
                d = "<cannot serialize>"
            out.append((c, d))
        return out

    def debug_print(self):
        """Prints this row to STDERR, within reason."""
        print '\n'.join(["%s: %s" % (k, v) for k, v in self.debug_items()])

    def save_to_disk(self):
        """Saves this row to disk."""
        # print >> sys.stderr, "Saving row to disk"
        root = ET.Element('entry')
        for k, v in self.items():
            se = ET.SubElement(root, k)
            se.text = str(v)
        new_data = ET.tostring(root)
        ###
        # This will block
        ###
        # print >> sys.stderr, "Writing [%s] to [%s]" % (new_data, self.filename)
        self.file.write(ET.tostring(root))

